package material;

import java.util.Date;

import commands.Command;

public class CommandThrowerImpl implements CommandThrower {

	private boolean active;		// L'etat de l'execution de la commande
	private Command command;	// La commande executee
	private long timer;			// La periode entre deux executions de la commande
	private float time;			// Le delai avant l'execution de la commande

	public CommandThrowerImpl() {
		active = true;
	}

	@Override
	public void setCommand(Command command) {
		this.command = command;
	}

	@Override
	public Command getCommand() {
		return command;
	}

	@Override
	public void setTimer(float timer) {
		Float tmpTimer = new Float(timer);
		this.timer = tmpTimer.longValue();
	}

	@Override
	public void setTime(float time) {
		this.time = time;
	}

	@Override
	public void run() {
		
		if(time > 0) {	// Si il y a un delai, alors on attend pendant ce delai puis on execute la commande
			try {
				Thread.sleep((long)time);
			} 
			catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			command.execute();
		}
		else {
			while(active) {	// Sinon, on execute la commande tant qu'elle n'est pas desactivee

				long startTime = new Date().getTime();
				long remainingTime = timer;
				boolean finish = false;
				command.execute();
				
				do {
					try {
						Thread.sleep(remainingTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					long currentTime = new Date().getTime();
					
					if(currentTime < startTime + remainingTime) {
						remainingTime = remainingTime - (currentTime - startTime);
						startTime = currentTime;
						finish = false;
					}
					else {
						finish = true;
					}
				} 
				while(!finish);
			}
		}
	}

	public void stopCommand() {
		active = false;
	}

	public boolean isActive() {
		return active;
	}

}
